<?php
/**
 * view: index/index
 * @var Cs_Service\Controller\Index
 * @var \Ke\Web\Context $this
 * @var \Ke\Web\Web     $web
 * @var string          $content
 */


$projects = $this->projects ?? [];
$servers = $this->servers ?? [];
$project = $this->project ?? new \CSService\Model\Project\Project();
$commands = $this->commands ?? [];
$userId = $this->user->id;
?>
<div>
	<div class="ui simple dropdown item">
		<strong><?php print ($project->isNew() ? '选择项目' : '项目: ' . $project->name) ?></strong> <i
			class="dropdown icon"></i>
		<div class="menu">
			<?php
			/** @var \CSService\Model\Project\Project $proj */
			foreach ($projects as $proj) {
				?>
				<a href="<?php print $this->web->http->newUri('',
					['p' => $proj->id]) ?>" class="item"><?php print $proj->name; ?></a>
				<?php
			}
			?>
		</div>
	</div>
	<ul class="ui list">

	</ul>
</div>
<?php
if ($project->isNew()) {
	$this->html->tag('div', '未指定项目，请先选择项目！', 'class="ui error message"');

}
?>

<?php
if ($project->isNew())
	return true;
?>
<table class="ui table selectable">
	<thead>
	<tr>
		<th class="collapsing">服务器</th>
		<th>操作</th>
		<th width="70%" class="center aligned">日志</th>
	</tr>
	</thead>
	<tbody>
	<?php
	/** @var \CSService\Model\Server\Server $server */
	foreach ($servers as $index => $server) {
		$webSocketAddress = $server->lan_ip . ':' . CS_WS_PORT;
		?>
		<tr>
			<td class="top aligned"><?php print $server->lan_ip . '<br />' . $server->name; ?></td>
			<td class="top aligned">
				<?php
				$groups = [];
				$buffer = [];
				$lastGroupId = -1;
				/** @var \CSService\Model\Command\Command $command */
				foreach ($commands as $command) {
					if ($lastGroupId !== $command->group_id) {
						$lastGroupId = $command->group_id;
						if (!empty($buffer))
							$groups[] = $this->html->mkTag('div', implode('<div class="or"></div>', $buffer),
								['class' => 'mini ui buttons']);
						$buffer = [];
					}
					$buffer[] = $this->html->mkButton($command->show_name, 'button', [
						'class'        => 'ui button command-btn',
						'data-id'      => "#log_{$index}",
						'data-ws'      => $webSocketAddress,
						'data-command' => sprintf('[%s|%s|%s]', $server->lan_ip, $project->name, $command->name),
						'data-confirm' => $command->user_confirm,
					]);
				}
				if (!empty($buffer))
					$groups[] = $this->html->mkTag('div', implode('<div class="or"></div>', $buffer),
						['class' => 'mini ui buttons']);
				print implode('<div class="ui divider"></div>', $groups);
				?>
			</td>
			<td>
				<pre id="log_<?php print $index ?>" class="log"></pre>
			</td>
		</tr>
		<?php
	}
	?>
	</tbody>
</table>
<script type="text/javascript">
	(function ($) {

		var clients = {};
		var token = '<?php print $this->user->getWSToken(); ?>';

		var Client = function (server) {
			if (!clients[server]) {
				var me = this;
				this.server = server;
				this.isReady = false;
				var client = this.client = new WebSocket("ws://" + server + "/?t=" + token);
				client.onopen = function (event) {
					me.isReady = true;
					console.log(this.url + ' open!');
					if (me.holdCommand !== false) {
						me.send(me.holdCommand);
						me.holdCommand = false;
					}
				};
				client.onclose = function (event) {
					console.log(this.url + ' close!');
					delete(clients[me.server]);
				};
				client.onmessage = function (event) {
					var message = event.data;
					console.log('recive message from ' + me.server + ' : ' + message);
					me.log(message);
				};
//				client.onerror = function() {
//					console.log(event);
//					console.log(me.server + ' error!');
//				};
				clients[server] = this;
			}
			return clients[server];
		};

		Client.prototype = {
			holdCommand: false,
			commands: [],
			logEl: null,
			setLogEl: function (id) {
				this.logEl = $(id);
				return this;
			},
			getLogEl: function () {
				return this.logEl;
			},
			log: function (message) {
				var el = this.getLogEl();
				if (el) {
					var text = el.text();
//					if (text.length > 0)
//						text += '\r\n';
					el.text(text + message);
					el.scrollTop(el.prop('scrollHeight'));
				}
				return this;
			},
			send: function (command) {
				if (!command || command.length <= 0)
					return this;
				if (!this.isReady) {
					this.holdCommand = command;
				}
				else {
					this.client.send(command);
				}
				return this;
			}
		};

		$('.command-btn').click(function () {
			var btn = $(this);
			var ws = btn.attr('data-ws'), command = btn.attr('data-command');
			var isConfirm = btn.attr('data-confirm') > 0;
			if (ws && command.length > 0) {
				if ((isConfirm && confirm("你确定要执行这条命令吗？")) || !isConfirm) {
					var client = new Client(ws);
					client.send(command).setLogEl(btn.attr('data-id'));
				}
			}
			return false;
		});

	})(jQuery);

</script>